import { ComponentRegistry } from './ComponentRegistry.js';
import { DatabaseComponentRegistry } from './DatabaseComponentRegistry.js';
import { RepositoryFactory } from '../database/repositories/index.js';
import { CacheManager } from '../cache/index.js';
import type { ComponentInfo } from '../types/index.js';

/**
 * 组件注册表接口 - 统一不同实现的接口
 * 采用异步接口设计，兼容同步和异步实现
 */
export interface IComponentRegistry {
  // 核心方法 - 全部异步
  registerComponent(component: ComponentInfo): Promise<void>;
  getComponent(name: string): Promise<ComponentInfo | undefined>;
  getAllComponents(): Promise<ComponentInfo[]>;
  searchComponents(query: string, category?: string, limit?: number): Promise<ComponentInfo[]>;
  getComponentsByCategory(category: string): Promise<ComponentInfo[]>;
  
  // 扩展方法
  getPopularComponents?(limit?: number): Promise<ComponentInfo[]>;
  getCategories?(): Promise<string[]>;
  getStats?(): Promise<{
    totalComponents: number;
    categoryCounts: Array<{ category: string; count: number }>;
    popularComponents: ComponentInfo[];
  }>;
  clearAllCache?(): Promise<void>;
  isDatabaseBacked?(): boolean;
}

/**
 * 组件注册表工厂类
 */
export class ComponentRegistryFactory {
  private static memoryRegistry?: ComponentRegistry;
  private static databaseRegistry?: DatabaseComponentRegistry;

  /**
   * 获取内存版本的组件注册表（原有实现）
   */
  static getMemoryRegistry(): ComponentRegistry {
    if (!ComponentRegistryFactory.memoryRegistry) {
      ComponentRegistryFactory.memoryRegistry = new ComponentRegistry();
    }
    return ComponentRegistryFactory.memoryRegistry;
  }

  /**
   * 获取数据库版本的组件注册表
   */
  static async getDatabaseRegistry(
    repositories: RepositoryFactory,
    cacheManager?: CacheManager
  ): Promise<DatabaseComponentRegistry> {
    if (!ComponentRegistryFactory.databaseRegistry) {
      ComponentRegistryFactory.databaseRegistry = new DatabaseComponentRegistry(
        repositories,
        cacheManager
      );
      await ComponentRegistryFactory.databaseRegistry.initialize();
    }
    return ComponentRegistryFactory.databaseRegistry;
  }

  /**
   * 获取自适应注册表 - 优先使用数据库版本，降级到内存版本
   */
  static async getAdaptiveRegistry(
    repositories?: RepositoryFactory,
    cacheManager?: CacheManager
  ): Promise<IComponentRegistry> {
    try {
      // 尝试使用数据库版本
      if (repositories) {
        const dbRegistry = await ComponentRegistryFactory.getDatabaseRegistry(
          repositories,
          cacheManager
        );
        return new AdaptiveComponentRegistry(dbRegistry);
      }
    } catch (error: any) {
      console.warn('⚠️  数据库组件注册表初始化失败，降级到内存版本:', error?.message || error);
    }

    // 降级到内存版本
    const memoryRegistry = ComponentRegistryFactory.getMemoryRegistry();
    return new AdaptiveComponentRegistry(memoryRegistry);
  }

  /**
   * 重置所有实例（用于测试或重启）
   */
  static reset(): void {
    ComponentRegistryFactory.memoryRegistry = undefined;
    ComponentRegistryFactory.databaseRegistry = undefined;
  }
}

/**
 * 自适应组件注册表 - 提供统一的接口，内部适配不同实现
 */
class AdaptiveComponentRegistry implements IComponentRegistry {
  private registry: ComponentRegistry | DatabaseComponentRegistry;
  private isDatabaseRegistry: boolean;

  constructor(registry: ComponentRegistry | DatabaseComponentRegistry) {
    this.registry = registry;
    this.isDatabaseRegistry = registry instanceof DatabaseComponentRegistry;
  }

  // 注册组件 - 自适应同步/异步
  async registerComponent(component: ComponentInfo): Promise<void> {
    if (this.isDatabaseRegistry) {
      return await (this.registry as DatabaseComponentRegistry).registerComponent(component);
    } else {
      (this.registry as ComponentRegistry).registerComponent(component);
    }
  }

  // 获取组件 - 自适应同步/异步
  async getComponent(name: string): Promise<ComponentInfo | undefined> {
    if (this.isDatabaseRegistry) {
      return await (this.registry as DatabaseComponentRegistry).getComponent(name);
    } else {
      return (this.registry as ComponentRegistry).getComponent(name);
    }
  }

  // 获取所有组件 - 自适应同步/异步
  async getAllComponents(): Promise<ComponentInfo[]> {
    if (this.isDatabaseRegistry) {
      return await (this.registry as DatabaseComponentRegistry).getAllComponents();
    } else {
      return (this.registry as ComponentRegistry).getAllComponents();
    }
  }

  // 搜索组件 - 自适应同步/异步
  async searchComponents(
    query: string,
    category?: string,
    limit?: number
  ): Promise<ComponentInfo[]> {
    if (this.isDatabaseRegistry) {
      return await (this.registry as DatabaseComponentRegistry).searchComponents(
        query,
        category,
        limit
      );
    } else {
      return (this.registry as ComponentRegistry).searchComponents(query, category, limit);
    }
  }

  // 按分类获取组件 - 自适应同步/异步
  async getComponentsByCategory(category: string): Promise<ComponentInfo[]> {
    if (this.isDatabaseRegistry) {
      return await (this.registry as DatabaseComponentRegistry).getComponentsByCategory(category);
    } else {
      return (this.registry as ComponentRegistry).getComponentsByCategory(category);
    }
  }

  // 数据库版本专有的方法
  async getPopularComponents(limit: number = 10): Promise<ComponentInfo[]> {
    if (this.isDatabaseRegistry) {
      return await (this.registry as DatabaseComponentRegistry).getPopularComponents(limit);
    } else {
      // 内存版本的简单实现 - 返回前几个组件
      const all = (this.registry as ComponentRegistry).getAllComponents();
      return all.slice(0, limit);
    }
  }

  async getCategories(): Promise<string[]> {
    if (this.isDatabaseRegistry) {
      return await (this.registry as DatabaseComponentRegistry).getCategories();
    } else {
      // 内存版本的实现
      const all = (this.registry as ComponentRegistry).getAllComponents();
      const categories = [...new Set(all.map(comp => comp.category))];
      return categories;
    }
  }

  async getStats(): Promise<{
    totalComponents: number;
    categoryCounts: Array<{ category: string; count: number }>;
    popularComponents: ComponentInfo[];
  }> {
    if (this.isDatabaseRegistry) {
      return await (this.registry as DatabaseComponentRegistry).getStats();
    } else {
      // 内存版本的实现
      const all = (this.registry as ComponentRegistry).getAllComponents();
      const categoryMap = new Map<string, number>();
      
      all.forEach(comp => {
        categoryMap.set(comp.category, (categoryMap.get(comp.category) || 0) + 1);
      });

      return {
        totalComponents: all.length,
        categoryCounts: Array.from(categoryMap.entries()).map(([category, count]) => ({
          category,
          count,
        })),
        popularComponents: all.slice(0, 5),
      };
    }
  }

  async clearAllCache(): Promise<void> {
    if (this.isDatabaseRegistry) {
      await (this.registry as DatabaseComponentRegistry).clearAllCache();
    }
    // 内存版本无缓存，无需操作
  }

  /**
   * 检查是否为数据库版本
   */
  isDatabaseBacked(): boolean {
    return this.isDatabaseRegistry;
  }

  /**
   * 获取底层注册表实例
   */
  getUnderlyingRegistry(): ComponentRegistry | DatabaseComponentRegistry {
    return this.registry;
  }
}